﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace BuyTicket.Views
{
    /// <summary>
    /// WebBrowserWindow.xaml 的交互逻辑
    /// </summary>
    public partial class WebBrowserWindow : Window
    {
        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);

        public WebBrowserWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Maximized;
        }

        string m_Cookies;
        public void Navigate(string cookies, string url)
        {
            m_Cookies = cookies;
            SetCookies(url);
            myBrowser.Navigate(url);
        }

        void SetCookies(string url)
        {
            string[] sArry = Regex.Split(m_Cookies, ";");
            foreach (var str in sArry)
            {
                string[] cookie = Regex.Split(str, "=");
                if (cookie.Length == 2)
                    InternetSetCookie(url, cookie[0], cookie[1].Replace(";", "").Trim());
            }
        }

        private void myBrowser_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            //设置cookies
            SetCookies(e.Url.ToString());
        }

        private void myBrowser_NewWindow(object sender, System.ComponentModel.CancelEventArgs e)
        {
            string newUrl = myBrowser.Document.ActiveElement.GetAttribute("href");
            myBrowser.Navigate(newUrl);
            e.Cancel = true;
        }

  
    }
}
